package com.haojiang.mh.remote.ui.dialog

import android.content.Intent
import android.os.Bundle
import android.view.Gravity
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.LinearLayout
import androidx.core.os.bundleOf
import androidx.fragment.app.FragmentActivity
import androidx.fragment.app.FragmentTransaction
import com.haojiang.mh.AppContext
import com.haojiang.mh.R
import com.haojiang.mh.remote.base.BaseDialogFrag
import com.haojiang.mh.remote.bean.DeviceModifySuccessEvent
import com.haojiang.mh.remote.ui.activity.QrcodeActivity
import com.haojiang.mh.remote.utils.BleUtil.Companion.saveDeviceAlias
import kotlinx.android.synthetic.main.frag_dialog_modify.*
import org.greenrobot.eventbus.EventBus


class ModifyDialogFrag : BaseDialogFrag() {

    /**
     * 伴生函数
     */
    companion object {
//        private val CLASS_NAME = "class_name"
        private val BLE_ADDRESS = "ble_address"
        private val BLE_NAME = "ble_name"
        private val DEVICE_ALIAS = "device_alias"

        private val instance by lazy { ModifyDialogFrag() }

//        fun show(fragmentActivity: FragmentActivity, className: String, bleAddress: String, bleName: String, deviceAlias: String) {
        fun show(fragmentActivity: FragmentActivity, bleAddress: String, bleName: String, deviceAlias: String) {
            val fm = fragmentActivity.supportFragmentManager
            val transaction: FragmentTransaction = fm.beginTransaction()
            val fragment = fm.findFragmentByTag(ModifyDialogFrag::class.java.simpleName)
            if (fragment != null) {
                transaction.remove(fragment)
                transaction.commit()
            }

            instance.arguments = bundleOf(
//                CLASS_NAME to className,
                BLE_ADDRESS to bleAddress,
                BLE_NAME to bleName,
                DEVICE_ALIAS to deviceAlias
            )
            instance.show(fm, ModifyDialogFrag::class.java.simpleName)
        }
    }


    private val onClickListener = object : View.OnClickListener {
        override fun onClick(v: View?) {
            if (v != null) {
                when (v.id) {
                    R.id.tvReset -> {
                        if (bleName != null) {
                            etDeviceAlias.setText(bleName)
                        }
                    }
                    R.id.tvConfirm -> {
                        val deviceAlias = etDeviceAlias.text.toString().trim()
                        if (deviceAlias.length <= 0) {
                            showToast(AppContext.instance().getString(R.string.m_content_can_not_be_empty))
                            return
                        }
                        bleAddress.let {
                            if (saveDeviceAlias(bleAddress!!, deviceAlias)) {
                                dismiss()
//                                EventBus.getDefault().post(DeviceModifySuccessEvent(className!!, bleAddress!!, deviceAlias))
                                EventBus.getDefault().post(DeviceModifySuccessEvent(bleAddress!!, deviceAlias))
                            }
                        }
                    }
                    R.id.ivClose -> {
                        dismiss()
                    }
                }
            }
        }

    }

    //    private val mIPermissionCallback = IPermissionCallback {
//        QrcodeActivity.setScanerListener(onRxScanerListener)
//        scanQrcode()
//    }
//    private var className: String? = null
    private var bleAddress: String? = null
    private var bleName: String? = null
    private var deviceAlias: String? = null

    override fun onSubCreate(savedInstanceState: Bundle?) {
        setStyle(STYLE_NO_TITLE, R.style.fragment_dialog)
        if (arguments != null) {
//            className = arguments!!.getString(CLASS_NAME)
            bleAddress = arguments!!.getString(BLE_ADDRESS)
            bleName = arguments!!.getString(BLE_NAME)
            deviceAlias = arguments!!.getString(DEVICE_ALIAS)
//            LogUtil.e(bleAddress + "--" + bleName + "--" + deviceAlias)
        }
    }

    override fun onSubCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        return inflater.inflate(R.layout.frag_dialog_modify, container, false)
    }

    override fun onSubViewCreated(view: View, savedInstanceState: Bundle?) {
        dialog!!.setCancelable(true) //是否可以点击取消
        dialog!!.setCanceledOnTouchOutside(false) //dialog外面是否可以点击

        val params = dialog!!.window!!.attributes
        val context = context
        context?.let {
            //            params.width = (Util.getScreenWidth(context) * 0.7f).toInt()
            params.width = LinearLayout.LayoutParams.WRAP_CONTENT
            params.height = LinearLayout.LayoutParams.WRAP_CONTENT
            params.gravity = Gravity.CENTER
            //高度自己定义
            dialog!!.window!!.setLayout(params.width, params.height)
        }
    }


    override fun onSubActivityCreated(savedInstanceState: Bundle?) {
//        ivQrcode.setOnClickListener(View.OnClickListener {
//            context?.let {
//                if (!Util.checkBleStatus(it)) {
//                    return@OnClickListener
//                }
//            }
//            PermissionManager.getInstance().setIPermissionCallback(mIPermissionCallback)
//            PermissionManager.getInstance().requestPermission(
//                context,
//                arrayOf(
//                    Manifest.permission.ACCESS_FINE_LOCATION,
//                    Manifest.permission.CAMERA,
//                    Manifest.permission.READ_EXTERNAL_STORAGE,
//                    Manifest.permission.WRITE_EXTERNAL_STORAGE
//                )
//            )
//        })
        if (deviceAlias != null) {
            etDeviceAlias.setText(deviceAlias)
        }
        tvConfirm.setOnClickListener(onClickListener)
        ivClose.setOnClickListener(onClickListener)
        tvReset.setOnClickListener(onClickListener)

    }


//    private val onRxScanerListener = object : OnRxScanerListener {
//        override fun onSuccess(type: String?, result: Result?) {
//            result?.let {
//                val interfaceNo = result.text.trim()
//                if (interfaceNo.length < 4) {
//                    showToast(getString(R.string.m_interface_not_exist))
//                } else {
//                    searchInterface(interfaceNo)
//                }
//            }
//        }
//
//        override fun onFail(type: String?, message: String?) {
//        }
//    }


    override fun initDestroy() {
    }


    private fun scanQrcode() {
        startActivity(Intent(activity, QrcodeActivity::class.java))
    }
}